<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;

class Appuser extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'user_info';
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;
    // protected $insert = [
    //     'status' => 1,
    // ];
    /*定义方法 如果出现该字段则直接显示中文*/
    public function getsexAttr($value)
    {
        $data = ['1'=>"男",'0'=>"女"];
        return $data[$value];
    }
    public function getstatusAttr($value)
    {
        $data = ['-1'=>"删除",'0'=>"禁用",'1'=>"正常"];
        return $data[$value];
    }

    /**
     * [getDataList 列表]
     * @AuthorHTL
     * @DateTime  2017-02-10T22:19:57+0800
     * @param     [string]                   $keywords [关键字]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [t每页数量]
     * @return    [array]                             [description]
     */
    public function getDataList($keywords='', $page=1, $limit=15)
    {
      $map = array();
      $map['phone|id_card|name'] = ['like', '%'.trim($keywords).'%'];
      $dataCount = $this->where($map)->count();
      $map2['a.phone|a.id_card|a.name'] = ['like', '%'.trim($keywords).'%'];
      $list = $this
            ->alias('a')
            ->join('qh_user b','a.uid = b.uid')
            // ->field('a.name,a.uid,a.id,a.age,a.phone,a.sex,a.qq,a.zhima,b.status,b.last_login_time,b.reg_time')
            ->order('id desc')
            ->where($map2)
            ->page($page, $limit)
            ->select();
        $list = modelo2array($list);
        // dump($list);
        // die;
        foreach ($list as $key => $value) {
            $id_card = $list[$key]['id_card'];
            $phone   = $list[$key]['phone'];
            $list[$key]['is_black'] = model('BlackList')->is_black($id_card, $phone);
        }
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        return $data;
    }


    /**
     * [getDataById 根据主键获取详情]
     * @linchuangbin
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {
        $data=$this->alias('a')
            ->join('qh_user b','a.uid = b.uid')
            // ->field('b.username,b.phone,b.status,a.name,a.age,a.sex,a.qq,a.zhima,a.province')
            ->where('a.id',$id)
            ->find();
        return $data;
    }
    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param     [type]                   $param [description]
     * @param     [type]                   $id    [description]
     * @return    [type]                          [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }

        // 验证
/*        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }*/

        try {
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            return true;
        } catch(\Exception $e) {
            $this->error = '编辑失败';
            return false;
        }
    }
    public function getName($uid)
    {
        return $this->where('uid',$uid)->value("name");
    }
    public function getPhone($uid)
    {
        return $this->where('uid',$uid)->value("phone");
    }    
    public function resetDataById($id)
    {
        // 不能操作超级管理员
        if ($id == 1) {
            $this->error = '非法操作';
            return false;
        }
        $checkData = $this->where('uid',$id)->find();
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        /*if($checkData['status']!=1){
            $this->error = '该账户已被删除或禁用！';
            return false;
        }*/
        $param=array();
        $param['password']=123456;
        $param['password'] = user_md5($param['password'],$auth_key = 'qhdkb');
        $param['last_login_time']=date('Y-m-d H:i:s',time());;
        $res=Db::name('user')->where('uid',$id)->update($param);
        if($res){
            return true;
        }else{
            $this->error = '重置失败';
            return false;
        }
    }
    /**
     * 获取所有子孙
     */
    public function getAllChild($id, &$data = [])
    {
        $map['pid'] = $id;
        $childIds = $this->where($map)->column($this->getPk());
        if (!empty($childIds)) {
            foreach ($childIds as $v) {
                $data[] = $v;
                $this->getAllChild($v, $data);
            }
        }
        return $data;
    }
    public function enableData($ids = [], $status = 1, $delSon = false)
    {
      if (empty($ids)) {
        $this->error = '修改失败';
        return false;
      }
        // // 查找所有子元素
        // if ($delSon && $status === '0') {
        //     foreach ($ids as $k => $v) {
        //         $childIds = $this->getAllChild($v);
        //         $ids = array_merge($ids, $childIds);
        //     }
        //     $ids = array_unique($ids);
        // }
      $list=$this->where('id','in',$ids)->select();
      $list = modelo2array($list);
      $data['list'] = $list;
      $uids=array();
      foreach($data['list'] as &$v){
        $uids[]=$v['uid'];
      }
      try {
        Db::name('user')->where('uid','in',$uids)->setField('status', $status);
        return true;
      } catch (\Exception $e) {
        $this->error = '操作失败';
        return false;
      }
    }
    
    /**
     * [getInvitDataById 根据主键获取邀请人数详情]
     * @linchuangbin
     * @DateTime  
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getInvitDataById($uid,$page, $limit)
    {
        $dataCount = $this->alias('a')
                    ->join('qh_invite_code b','a.uid = b.uid')
                    ->where('puid',$uid)
                    ->count('b.id');
        
        $invitName = $this->where('uid',$uid)->field('name')->find();
        $invitName = json_decode($invitName);
        $list = $this
        ->where(1);
        // 若有分页
        if ($page && $limit) {
            $list = $this->page($page, $limit);
        }
        
        $list=$this->alias('a')
        ->join('qh_invite_code b','a.uid = b.uid')
        ->field('a.name,a.qq,a.phone,a.zhima,b.create_time')
        ->where('b.puid',$uid)
        ->select();
        
        $list = modelo2array($list);
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        $data['invitName'] = $invitName;
        return $data;
    }
    /**
     * [getdatas 获取单条数据]
     * @param  string $fiels [description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function getDatas($field = '*',$where = [])
    {
        return $this->field($field)->where($where)->find();
    }

}